package com.dz.usersystem.controller;

import cn.hutool.core.util.IdUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.StringUtils;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.dz.usersystem.config.AlipayConfig;
import com.dz.usersystem.entity.FilmUser;
import com.dz.usersystem.service.AlipayService;
import com.dz.usersystem.service.FilmUserService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@Slf4j
public class AlipayControl {


    @Resource
    private FilmUserService filmUserService;

    @GetMapping(value = "getPay")
    public String getPay(HttpServletResponse response, HttpServletRequest request,
                       @RequestParam(value = "count",required = true)String count,
                       @RequestParam(value = "message",required = true)String message,
                         @RequestParam(value = "id",required = true)String id) throws IOException {



        log.info("支付业务开始---------");
        response.setContentType("text/html;charset=UTF-8");
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        String simpleUUID = IdUtil.simpleUUID();
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = simpleUUID;
        //付款金额，必填
        String total_amount = count;
        //订单名称，必填
        String subject = message;
        //商品描述，可空
        String body = message;

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
            response.setContentType("text/html;charset=" + AlipayConfig.charset);
            response.getWriter().write(result);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            e.printStackTrace();
            response.getWriter().write("捕获异常出错");
            response.getWriter().flush();
            response.getWriter().close();

        }
        log.info("----支付业务结束----------------");
        log.info("----积分/积分记录 更新开始-------------");
        int t=999;
        char[] chars = message.toCharArray();
        char[] newChar = new char[99];

        for (int i = 0, z=0; i < chars.length; i++) {
            if (chars[i]=='元'){
                t=i;
            }else {
                if(i>t &&(chars[i] >='0' && chars[i] <= '9')){
                    newChar[z++]=chars[i];
                }
            }
        }
        String con =new String(newChar);
        log.info("积分:"+con);
        log.info("id"+id);


        FilmUser user =new FilmUser();
        if(id.length()>0){
            FilmUser user1 = filmUserService.queryById(id);
            log.info("user:"+user1.toString());
            try {
                int cc =Integer.parseInt(con.trim());
                int bb =Integer.parseInt(user1.getCount().trim());
                log.info("cc"+cc+"bb"+bb);
                String s = String.valueOf(cc+bb);
                log.info("加起来的积分"+s);
                user.setCount(s);
                user.setId(id);
                Date date =new  Date();
                SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

                String str =  "时间:"+ simpleDateFormat.format(date)+" "+  user1.getName() +"充值了"+count+"元";
                String jilu = user1.getJilu();
                if (jilu.length()==0){
                     jilu=str;
                }else {
                    jilu=jilu+","+str;
                }
                user.setJilu(jilu);
                FilmUser update = filmUserService.update(user);
                System.out.println("count:"+count);
                System.out.println(update);
                log.info("------积分更新结束-----");
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }







        return "success";
    }





}
